package com.kgc.ssm.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

/**
 * Created On : 2022/8/11.
 * <p>
 * Author : zhukang
 * <p>
 * Description: 字符集编码过滤器
 */
@WebFilter(filterName = "characterEncodingFilter", urlPatterns = "/*", initParams = {
        @WebInitParam(name = "encoding", value = "utf-8")
})
public class CharacterEncodingFilter implements Filter {

    private String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.encoding = filterConfig.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // 设置post请求字符集
        request.setCharacterEncoding(encoding);

        // 设置响应字符集
        response.setCharacterEncoding(encoding);

        // 放行请求
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
